package org.xmx0632.connector.service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.protocol.message.Request;

/**
 * 用于发送消息到外部系统,实现可替换
 *
 */
@Component
public class MessageSender {

	public static final Logger LOG = LoggerFactory.getLogger(MessageSender.class);

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	public void send(final Request message) {
		try {
			LOG.debug("send message:{}", message);
			jmsTemplate.send(new MessageCreator() {
				public Message createMessage(Session session) throws JMSException {
					ObjectMessage msg = session.createObjectMessage();
					msg.setObject(message);
					return msg;
				}
			});
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}

}
